const app = getApp();
const api = require('../../../../ws_micro_shop/utils/api.js');
const { handleStatisticsShare, wxappjump } = require('../../../api/common');
const { loadingMiddleware } = require('../../../common/utils/util');
const { qyWXCheckSeesion } = require('../../../../common/utils/ws/ws-wxwork');


Page({
  data: {
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '暂无可分享文章~',
    },
    list: [],
    isData: false,
    page: 1,
    canPullUp: true,
    loadingText: '下拉加载',
    param_id:'',
    imgUrl: app.imgUrl
  },

  onShow() {
    wx.hideShareMenu();
    // wx.setNavigationBarTitle({
    //   title: '分享文章',
    // });
    this.setData(
      {
        isData:false,
        list:[],
        stroeId: app.ws_micro_shop_globalData.shopid,
        rolesId: app.ws_micro_shop_globalData.guide_id,
        page:1
      },
      () => {
        this.getArticle();
        app.isWXWork && qyWXCheckSeesion({});
      },
    );
  },

  getArticle() {
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    const { stroeId: shop_id = '', page, list } = this.data;
    loadingMiddleware.before(this);
    app.ws_micro_shoprequest({
      url: api.default.topic_list,
      data: {
        from_guide: 1,
        shop_id,
        page,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const newList = res.data.list;
          if (newList.length <= 0) {
            loadingMiddleware.after(res, this);
            return;
          }
          this.setData({
            list: [...list, ...newList],
          }, () => {
            loadingMiddleware.after(res, this);
          });
        }
      },
      fail: res => {
        loadingMiddleware.after(res, this);
      },
      complete: res => {
        this.setData({
          isData: true,
        }, () => {
          wx.hideLoading();
        });
      },
    });
  },

  onReachBottom() {
    let { canPullUp, page } = this.data;

    if (canPullUp) {
      this.setData(
        {
          page: ++page,
        },
        () => {
          this.getArticle();
        },
      );
    }
  },

  onShareAppMessage(res) {
    wx.showLoading({
      title: '正在加载',
    });
    if (res.from === 'button') {
      const { stroeId = '', rolesId = '',list} = this.data;
      const { param_id = '', share_pic: imageUrl = '', share_title='' } = res.target.dataset;
      const { module: moduleName } = app.siteInfo;
      const path = `/ws_micro_shop/pages/topic/topic?id=${param_id}&guide_id=${rolesId}&shopid=${stroeId}`;
      this.setData({
        param_id
      })
      return {
        path: app.util.spliceSharePath(path, '4', moduleName),
        title: share_title,
        imageUrl,
      };
    }
  },

  onNavigate(e) {
    let { url = '', ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  },

  onUserOpStatistic(e) {
    // if (e.op == 'share') {
      const type = 7;
      const { param_id = '' } = this.data;
      handleStatisticsShare({ type, param_id });
    // }
      wx.hideLoading();
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  showShareModal(e) {
    let dataset = e.target.dataset;
    this.setData({
      ...dataset,
      share_modal_active: 'active',
    });
  },

  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },

  wxappJump() {
    let { titletype, path, stroeId = '', rolesId = '', param_id } = this.data;
    let appid =  wx.getStorageSync('appid');
    path = path + '&shopid=' + stroeId + '&from=fromB&guide_id=' + rolesId;
    wxappjump(appid, path, 7, param_id, this);
  },

  getGoodsQrcode() {
    let _this = this;
    let { param_id = '', rolesId = '', goods_qrcode = '', share_pic = '', type } = _this.data;
    _this.setData({
      goods_qrcode_active: 'active',
    });
    if (goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.staff.topic_qrcode,
      data: {
        id: param_id,
        guide_id: rolesId,
        share_type: 7,
      },
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            goods_qrcode: res.data.pic_url,
          });
          handleStatisticsShare({ type, param_id });
        }
        if (res.code === 1) {
          _this.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
    // gatherAction &&
    //   gatherAction('userGetGoodsQrcode', 'success', { goodsID: this.data.id });
  },

  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      share_modal_active: '',
      goods_qrcode: ''
    });
  },
  saveGoodsQrcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          _this.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
    // gatherAction &&
    //   gatherAction('userSaveGoodsQrcode', 'success', { goodsID: this.data.id });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '软文海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },
  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
});
